/*
 * @(#)RespondingQueryClient.java
 * Date 2013-10-25
 * Version 1.0
 * Author Jim Horner
 * Copyright (c)2012
 */


package us.hornerscorners.lamppost.xca.client;

import javax.enterprise.context.ApplicationScoped;

import javax.xml.ws.BindingProvider;

import javax.xml.ws.soap.AddressingFeature;

import ihe.iti.xds_b._2007.RespondingGatewayQueryPortType;
import ihe.iti.xds_b._2007.RespondingGatewayQueryService;

import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryRequest;
import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryResponse;

import us.hornerscorners.lamppost.config.EndpointConfig;

import us.hornerscorners.lamppost.model.audit.AuditContext;

import us.hornerscorners.lamppost.registry.service.AtnaRegistryService;
import us.hornerscorners.lamppost.registry.service.IStoredQueryService;

import us.hornerscorners.lamppost.ws.AbstractWSClient;
import us.hornerscorners.lamppost.ws.AddressCallback;


/**
 * Class description
 *
 *
 * @version        v1.0, 2013-10-25
 * @author         Jim Horner
 */
@ApplicationScoped
public class RespondingQueryClient extends AbstractWSClient
        implements IStoredQueryService {

    /** Field description */
    private final AtnaRegistryService atnaService;

    /** Field description */
    private final RespondingGatewayQueryService queryService;

    /**
     * Constructs ...
     *
     *
     * @param atnaService
     * @param cfg
     */
    public RespondingQueryClient(AtnaRegistryService atnaService, EndpointConfig cfg) {

        this(atnaService, new RespondingGatewayQueryService(), cfg);
    }

    /**
     * Constructs ...
     *
     *
     * @param atnaService
     * @param queryService
     * @param cfg
     */
    public RespondingQueryClient(AtnaRegistryService atnaService,
                                 RespondingGatewayQueryService queryService,
                                 EndpointConfig cfg) {

        super(cfg);
        this.queryService = queryService;
        this.atnaService = atnaService;
    }

    /**
     * Method description
     *
     *
     * @param body
     *
     * @return
     */
    @Override
    public AdhocQueryResponse executeStoredQuery(AuditContext auditContext,
            AdhocQueryRequest body) {

        AdhocQueryResponse result = null;

        RespondingGatewayQueryPortType port =
            this.queryService.getRespondingGatewayQueryPortSoap12(
                new AddressingFeature(true, true));

        AddressCallback addressCallback = 
                configureBindingProvider(auditContext, (BindingProvider) port);

        result = port.respondingGatewayCrossGatewayQuery(body);
        
        AuditContext outgoingContext = parseOutgoingContext(auditContext,
                                           addressCallback);
        
        this.atnaService.sendQueryRequestAuditMessage(outgoingContext, body, result);

        return result;
    }
}
